/**
 * 工作流管理器
 * 提供统一的工作流管理接口
 */

import { workflowApi, type WorkflowType, type WorkflowParams } from './workflowApi'
import { type TaskProgressResponse, type TaskResultResponse } from './lightcc-api'
import {
  SpaTextApi,
  SpaStyleApi,
  LightModifyApi,
  SingleEditApi,
  DoubleEditApi,
  BilliardsTextApi,
  BilliardsStyleApi,
  ImageToVideoApi,
  InpaintingApi,
  YogaTextApi,
  YogaStyleApi,
  MigrationApi,
  UpscaleGeminiApi
} from './workflowApis'

// 工作流执行选项
export interface WorkflowExecutionOptions {
  onProgress?: (progress: TaskProgressResponse) => void
  onError?: (error: Error) => void
  onComplete?: (result: TaskResultResponse) => void
}

// 工作流管理器类
export class WorkflowManager {
  /**
   * 获取所有可用的工作流
   */
  static getAvailableWorkflows() {
    return workflowApi.getAvailableWorkflows()
  }

  /**
   * 获取工作流配置信息
   */
  static getWorkflowInfo(type: WorkflowType) {
    return workflowApi.getWorkflowConfig(type)
  }

  /**
   * 执行 SPA生图（手写提示词）
   */
  static async spaTextGenerate(
    prompt: string,
    options: {
      negativePrompt?: string
      width?: number
      height?: number
      steps?: number
      cfg?: number
      seed?: number
      onProgress?: (progress: TaskProgressResponse) => void
    } = {}
  ): Promise<TaskResultResponse> {
    return await SpaTextApi.generateImage(prompt, options)
  }

  /**
   * 执行 SPA生图（风格参考）
   */
  static async spaStyleGenerate(
    prompt: string,
    styleImage: File,
    options: {
      negativePrompt?: string
      width?: number
      height?: number
      steps?: number
      cfg?: number
      seed?: number
      onProgress?: (progress: TaskProgressResponse) => void
    } = {}
  ): Promise<TaskResultResponse> {
    return await SpaStyleApi.generateImage(prompt, styleImage, options)
  }

  /**
   * 执行光线修改
   */
  static async lightModify(
    inputImage: File,
    options: {
      prompt?: string
      intensity?: number
      temperature?: number
      contrast?: number
      onProgress?: (progress: TaskProgressResponse) => void
    } = {}
  ): Promise<TaskResultResponse> {
    return await LightModifyApi.modifyLight(inputImage, options)
  }

  /**
   * 执行单图指令编辑
   */
  static async singleEdit(
    inputImage: File,
    prompt: string,
    options: {
      negativePrompt?: string
      strength?: number
      steps?: number
      cfg?: number
      onProgress?: (progress: TaskProgressResponse) => void
    } = {}
  ): Promise<TaskResultResponse> {
    return await SingleEditApi.editImage(inputImage, prompt, options)
  }

  /**
   * 执行双图编辑参考风格
   */
  static async doubleEdit(
    inputImage: File,
    styleImage: File,
    prompt: string,
    options: {
      negativePrompt?: string
      styleStrength?: number
      steps?: number
      cfg?: number
      onProgress?: (progress: TaskProgressResponse) => void
    } = {}
  ): Promise<TaskResultResponse> {
    return await DoubleEditApi.editWithStyle(inputImage, styleImage, prompt, options)
  }

  /**
   * 执行台球生图（手写提示词）
   */
  static async billiardsTextGenerate(
    prompt: string,
    options: {
      negativePrompt?: string
      width?: number
      height?: number
      steps?: number
      cfg?: number
      seed?: number
      onProgress?: (progress: TaskProgressResponse) => void
    } = {}
  ): Promise<TaskResultResponse> {
    return await BilliardsTextApi.generateImage(prompt, options)
  }

  /**
   * 执行台球生图（风格参考）
   */
  static async billiardsStyleGenerate(
    prompt: string,
    styleImage: File,
    options: {
      negativePrompt?: string
      width?: number
      height?: number
      steps?: number
      cfg?: number
      seed?: number
      onProgress?: (progress: TaskProgressResponse) => void
    } = {}
  ): Promise<TaskResultResponse> {
    return await BilliardsStyleApi.generateImage(prompt, styleImage, options)
  }

  /**
   * 执行图生视频
   */
  static async imageToVideo(
    inputImage: File,
    options: {
      prompt?: string
      videoLength?: number
      fps?: number
      motionStrength?: number
      onProgress?: (progress: TaskProgressResponse) => void
    } = {}
  ): Promise<TaskResultResponse> {
    return await ImageToVideoApi.generateVideo(inputImage, options)
  }

  /**
   * 执行局部重绘
   */
  static async inpainting(
    inputImage: File,
    maskImage: File,
    prompt: string,
    options: {
      negativePrompt?: string
      strength?: number
      steps?: number
      cfg?: number
      onProgress?: (progress: TaskProgressResponse) => void
    } = {}
  ): Promise<TaskResultResponse> {
    return await InpaintingApi.inpaint(inputImage, maskImage, prompt, options)
  }

  /**
   * 执行瑜伽生图（手写提示词）
   */
  static async yogaTextGenerate(
    prompt: string,
    options: {
      negativePrompt?: string
      width?: number
      height?: number
      steps?: number
      cfg?: number
      seed?: number
      onProgress?: (progress: TaskProgressResponse) => void
    } = {}
  ): Promise<TaskResultResponse> {
    return await YogaTextApi.generateImage(prompt, options)
  }

  /**
   * 执行瑜伽生图（风格参考）
   */
  static async yogaStyleGenerate(
    prompt: string,
    styleImage: File,
    options: {
      negativePrompt?: string
      width?: number
      height?: number
      steps?: number
      cfg?: number
      seed?: number
      onProgress?: (progress: TaskProgressResponse) => void
    } = {}
  ): Promise<TaskResultResponse> {
    return await YogaStyleApi.generateImage(prompt, styleImage, options)
  }

  /**
   * 执行迁移
   */
  static async migration(
    inputImage: File,
    styleImage: File,
    options: {
      prompt?: string
      styleStrength?: number
      steps?: number
      cfg?: number
      onProgress?: (progress: TaskProgressResponse) => void
    } = {}
  ): Promise<TaskResultResponse> {
    return await MigrationApi.migrateStyle(inputImage, styleImage, options)
  }

  /**
   * 执行高清放大（gemini）
   */
  static async upscaleGemini(
    inputImage: File,
    options: {
      scaleFactor?: number
      modelName?: string
      onProgress?: (progress: TaskProgressResponse) => void
    } = {}
  ): Promise<TaskResultResponse> {
    return await UpscaleGeminiApi.upscaleImage(inputImage, options)
  }

  /**
   * 通用工作流执行方法
   */
  static async executeWorkflow(
    type: WorkflowType,
    params: WorkflowParams,
    options: WorkflowExecutionOptions = {}
  ): Promise<TaskResultResponse> {
    try {
      const result = await workflowApi.executeWorkflow(type, params, options.onProgress)
      
      if (options.onComplete) {
        options.onComplete(result)
      }
      
      return result
    } catch (error) {
      if (options.onError) {
        options.onError(error as Error)
      }
      throw error
    }
  }

  /**
   * 批量执行工作流
   */
  static async batchExecute(
    workflows: Array<{
      type: WorkflowType
      params: WorkflowParams
      options?: WorkflowExecutionOptions
    }>
  ): Promise<TaskResultResponse[]> {
    const results: TaskResultResponse[] = []
    
    for (const workflow of workflows) {
      try {
        const result = await this.executeWorkflow(
          workflow.type,
          workflow.params,
          workflow.options
        )
        results.push(result)
      } catch (error) {
        console.error(`批量执行工作流失败 (${workflow.type}):`, error)
        // 可以选择继续执行其他工作流或停止
        throw error
      }
    }
    
    return results
  }

  /**
   * 获取工作流执行历史（需要实现存储机制）
   */
  static getExecutionHistory(): any[] {
    // 这里需要实现历史记录存储和检索
    // 可以从 localStorage 或后端 API 获取
    return []
  }

  /**
   * 保存工作流执行结果
   */
  static saveExecutionResult(result: TaskResultResponse, metadata?: any): void {
    // 这里需要实现结果存储
    // 可以保存到 localStorage 或发送到后端
    console.log('保存执行结果:', result, metadata)
  }
}

// 创建单例实例
export const workflowManager = new WorkflowManager()

